package com.pat.jrgwt.client;

public class JsonRequest
{
    public static void get(String url, JsonRequestHandler handler)
    {
        String callbackName = "JSONCallback" + handler.hashCode();
        get(url + callbackName, callbackName, handler);
    }

    public static void get(String url, String callbackName, JsonRequestHandler handler)
    {
        createCallbackFunction(handler, callbackName);
        addScript(url);
    }

    public static native void addScript(String url) /*-{
		var scr = document.createElement("script");
		scr.setAttribute("language", "JavaScript");
		scr.setAttribute("src", url);

        // TODO: make timeout f-tion
        
		document.getElementsByTagName("body")[0].appendChild(scr);
    }-*/;

    private native static void createCallbackFunction(JsonRequestHandler obj, String callbackName)/*-{
		tmpcallback = function(j) {
			obj.@com.pat.jrgwt.client.JsonRequestHandler::onRequestCompleted(Lcom/google/gwt/core/client/JavaScriptObject;)(j);
		};
		eval("window." + callbackName + "=tmpcallback");
    }-*/;
}
